import router from './router'
import Router from 'vue-router'
import { constantRouterMap,asyncPluginsMap,asyncRouterMap } from '@/router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
NProgress.configure({ showSpinner: false })

function hasPermission(roles, permissionRoles) {
  console.log(roles, permissionRoles, '=================hasPermission')
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = store.getters.isToLogin ? ['/login'] : []
router.beforeEach((to, from, next) => {
  console.log("跳转之前",to,from,next)

  // if(!!from.query.bus_id && !!!to.query.bus_id){
  //   console.log('修改之后',{ ...to,query: {...to.query,bus_id:from.query.bus_id}});
  //   next({ ...to,query: {...to.query,bus_id:from.query.bus_id}})
  //   // to.query = {...to.query,bus_id:from.query.bus_id}
  // }
  const needAddBusIdToQuery = !!from.query.bus_id && !!!to.query.bus_id
  const bus_id = needAddBusIdToQuery ? from.query.bus_id : ''

  NProgress.start()
  // console.log(to.path, store.getters.rolesDefult, 'console.log.path')
  console.log('store+++++++++++++store',store.state.secondNav);
  //获取当前路由（name）
  const nowPath = to.path.split('/').pop();
  // console.log('store+++++++++++++storeto.path',);

  
  /**
   * 新版应用路由
   */
  if(store.state.secondNav.navData.length == 0){
    //检测当前路由是否为应用的三级路由
    // console.log('asyncPluginsMapasyncPluginsMap',asyncPluginsMap);
    if (asyncPluginsMap instanceof Array && asyncPluginsMap.length > 0) {
      //存在子路由
      if (
        asyncPluginsMap[0] instanceof Object &&
        !!asyncPluginsMap[0].children
      ) {
        const rootPaths = asyncPluginsMap[0].children,
              secondRoot = [];
              let isApplicationRoot = false;//是否应用二级路由没有

            // console.log('当前路由名称',nowPath);
        rootPaths.map((root) => {
          // 验证是否在应用中
          if(root.name == nowPath){
            //是应用二级路由
            isApplicationRoot = !isApplicationRoot;
          }
          // 主模块，并且模块存在
          if (
            !!root.app_is_model &&
            !!root.app_model &&
            !!root.meta &&
            !!root.meta.display &&
            !!root.meta.display.children &&
            root.meta.display.children instanceof Array &&
            root.meta.display.children.length > 0 
            &&
            root.meta.display.children.indexOf(nowPath) != -1
          ) {
            //当前为三级路由
            isApplicationRoot = false;
            //当前路由为应用级路由三级子路由，获取同等级三级路由
            rootPaths.map(res_1 => {
              root.meta.display.children.map(res_2 => {
                if(res_1.name == res_2){
                  secondRoot.push(res_1);
                }
              })
            })
            // console.log('应用级路由',root);
          }
        });

        //如果是三级路由，那么入原本一级路由应用子集
        if(secondRoot.length == 0 && isApplicationRoot){
          // console.log('constantRouterMap',asyncRouterMap);
          asyncRouterMap.map(item_root => {
            if(item_root.path == '/applicationNew'){
              item_root.children.map(item_root_item => {
                secondRoot.push({...item_root_item,isApplication:true});
              })
             
            }
          })
        }

        store.commit('SET_NAV_DATA',secondRoot);
      }
    }
  }

  if (to.path !== '/login') {
    document.querySelector('#_weliamtitle').innerHTML = to.meta.title || '管理平台'
  }

  if (to.path === '/dashboard') {
    store.dispatch('setRedirect', to.path)
  }

  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/',query:{
        bus_id
      } })
      NProgress.done()
    } else {
      // console.log(store.getters.inEdition, 'inEdition')
      if (store.getters.roles.length === 0) {
        const rolesDefult = store.getters.rolesDefult
        const routerPath = store.getters.routerPath
        store.dispatch('ChangeRoles', { 'roles': rolesDefult, 'path': routerPath }).then(() => {
          // console.log({ ...to, replace: true }, store.getters.addRouters, 'store.getters.addRouters')
          router.matcher = new Router({
            routes: [...constantRouterMap]
          }).matcher

          // console.log(store.getters.addRouters, 'matcher1')
          router.addRoutes(store.getters.addRouters)
          // console.log(to, router, 'matcher2')
          next({ ...to,query: {...to.query,bus_id}, replace: true })
        }).catch(err => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || '请重新登录!~')
            next({ path: '/',query: {bus_id}, replace: true })
          })
        })
      } else {
        store.dispatch('SetRrouterBefore', from.path)
        if (hasPermission(store.getters.roles, to.meta.roles)) {
          next({...to,query: {...to.query,bus_id}})
        } else {
          next({ path: '/401', replace: true, query: { noGoBack: true,bus_id } })
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next({ ...to,query: {...to.query,bus_id}, replace: true })
    } else {
      if (store.getters.isToLogin) {
        next(`/login?redirect=${to.path}&bus_id=${bus_id}`)
      } else {
        location.href = `${location.protocol}//${location.hostname}`
      }
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }

})

router.afterEach((to, from, next) => {
  console.log('跳转之后',to, from, next);
  store.dispatch('toggleDropdown', (to.meta && to.meta.noDropdown))
  NProgress.done()
})

router.onReady(() => {
})
